package cn.wuxing.mediation.framework.web.service;

import cn.wuxing.mediation.common.constant.Constants;
import cn.wuxing.mediation.common.core.domain.entity.SysUser;
import cn.wuxing.mediation.common.core.domain.model.LoginBody;
import cn.wuxing.mediation.common.core.domain.model.LoginUser;
import cn.wuxing.mediation.common.core.redis.RedisCache;
import cn.wuxing.mediation.common.exception.ServiceException;
import cn.wuxing.mediation.common.utils.DESCrypt;
import cn.wuxing.mediation.common.utils.DateUtils;
import cn.wuxing.mediation.common.utils.MessageUtils;
import cn.wuxing.mediation.common.utils.ip.IpUtils;
import cn.wuxing.mediation.framework.manager.AsyncManager;
import cn.wuxing.mediation.framework.manager.factory.AsyncFactory;
import cn.wuxing.mediation.system.service.ISysUserService;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class AvoidLoginService {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private RedisCache redisCache;


    /**
     * 登录验证
     * @param loginBody
     * @return 结果
     */
    public String smsLogin(LoginBody loginBody) throws Exception{

        // 用户验证
        Authentication authentication = null;

        String phone = loginBody.getPhone();

        SysUser user = userService.selectUserByPhoneNumber(phone);

        //redis 存储
//        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        Object verificationCode = redisCache.getCacheObject(phone);
        if(verificationCode!=null){
            if(!loginBody.getVerificationCode().equals(verificationCode.toString())){
                throw new ServiceException(MessageUtils.message("验证码不正确"));
            }
        }else{
            throw new ServiceException(MessageUtils.message("手机号码不存在"));
        }

        if(user==null){
            throw new ServiceException(MessageUtils.message("电话号码不存在"));
        }

        // 创建 UserDetails，并设置权限
        UserDetails userDetails = new CustomUserDetailsService(userService, permissionService).createLoginUser(user);

        authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userDetails.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 登录验证
     * @param userInfo
     * @return 结果
     */
    public String dsfLogin(String userInfo) throws Exception{

        byte[] decrypted = DESCrypt.decrypt(userInfo);
        String userInfoDetail = new String(decrypted, "UTF-8");

        // 将 String 转换为 JSONObject
        JSONObject jsonObject = JSONObject.parseObject(userInfoDetail);

        // 用户验证
        Authentication authentication = null;
        // 使用 code 进行钉钉登录逻辑，获取用户信息
        String employeeCode = jsonObject.getString("employeeCode");

        SysUser user = userService.selectUserByEmployee(employeeCode);

        // 创建 UserDetails，并设置权限
        UserDetails userDetails = new CustomUserDetailsService(userService, permissionService).createLoginUser(user);

        authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userDetails.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);

    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
